package com.fort.teachermanagementsys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fort.teachermanagementsys.entity.Course;
import com.fort.teachermanagementsys.entity.Schedule;
import com.fort.teachermanagementsys.service.ClassManagementService;
import com.fort.teachermanagementsys.service.CourseService;
import com.fort.teachermanagementsys.service.ScheduleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "课次管理")
@RestController
@RequestMapping("/sche")
public class ScheduleController {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ClassManagementService classManagementService;

    @ApiOperation("添加课次")
    @PostMapping("/schedule")
    public ResponseEntity<?> addSchedule(@RequestBody Schedule schedule) {
        Map<String, Object> response = new HashMap<>();
        if (schedule.getTopic() == null || schedule.getCourseId() == null || schedule.getClassId() == null ||
                schedule.getDate() == null || schedule.getTime() == null || schedule.getInstructor() == null ||
                schedule.getClassroom() == null || schedule.getDuration() == null || schedule.getMode() == null) {
            response.put("code", 400);
            response.put("message", "请填写所有必填字段");
            return ResponseEntity.badRequest().body(response);
        }
        if (courseService.getById(schedule.getCourseId()) == null) {
            response.put("code", 400);
            response.put("message", "无效的课程ID");
            return ResponseEntity.badRequest().body(response);
        }
        scheduleService.addSchedule(schedule);
        response.put("code", 200);
        response.put("message", "添加成功");
        return ResponseEntity.ok(response);
    }

    @ApiOperation("获取课次列表")
    @GetMapping("/schedule")
    public ResponseEntity<Map<String, Object>> getSchedules(
            @RequestParam Integer classId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (classId == null || classManagementService.getById(classId) == null) {
                response.put("code", 400);
                response.put("message", "无效的班级ID");
                return ResponseEntity.badRequest().body(response);
            }
            LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Schedule::getClassId, classId);
            if (startDate != null && !startDate.isEmpty()) {
                queryWrapper.ge(Schedule::getDate, LocalDate.parse(startDate).atStartOfDay());
            }
            if (endDate != null && !endDate.isEmpty()) {
                queryWrapper.le(Schedule::getDate, LocalDate.parse(endDate).atTime(23, 59, 59));
            }
            Page<Schedule> page = new Page<>(current, size);
            Page<Schedule> result = scheduleService.page(page, queryWrapper);
            Map<String, Object> data = new HashMap<>();
            data.put("records", result.getRecords());
            data.put("total", result.getTotal());
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取课次列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @ApiOperation("修改课次名称")
    @PutMapping("/schedule/{id}")
    public ResponseEntity<Map<String, Object>> updateSchedule(@PathVariable Integer id, @RequestBody Schedule schedule) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (schedule.getTopic() == null || schedule.getTopic().isEmpty()) {
                response.put("code", 400);
                response.put("message", "课次名称不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            Schedule existing = scheduleService.getById(id);
            if (existing == null) {
                response.put("code", 400);
                response.put("message", "课次不存在");
                return ResponseEntity.badRequest().body(response);
            }
            existing.setTopic(schedule.getTopic());
            existing.setUpdatedAt(java.time.LocalDateTime.now());
            scheduleService.updateById(existing);
            response.put("code", 200);
            response.put("message", "修改成功");
            response.put("data", existing);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "修改失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @ApiOperation("删除课次")
    @DeleteMapping("/schedule/{id}")
    public ResponseEntity<Map<String, Object>> deleteSchedule(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (scheduleService.getById(id) == null) {
                response.put("code", 400);
                response.put("message", "课次不存在");
                return ResponseEntity.badRequest().body(response);
            }
            scheduleService.removeById(id);
            response.put("code", 200);
            response.put("message", "删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    @ApiOperation("获取所有课程")
    @GetMapping("/courses")
    public ResponseEntity<Map<String, Object>> getCourses() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Course> courses = courseService.getAllCourses();
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", courses);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取课程列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
